<?php
namespace Home\Controller;

use Think\Controller;
use Think\Log;
use Common\Service\WXBizDataCrypt;
use Common\Service\WXBizDataCryptAes;
use Common\Service\Curl;

class ApiController extends Controller
{

    public function __constract()
    {
        vendor('Weixinpay.WxPayPubHelper');
    }


    function index()
    {
        //         初始化值对象
        $input = new WxPayUnifiedOrder();
        //         文档提及的参数规范：商家名称-销售商品类目
        $input->SetBody("testceshi");
        //         订单号应该是由小程序端传给服务端的，在用户下单时即生成，demo中取值是一个生成的时间戳
        $input->SetOut_trade_no(time() . '');
        //         费用应该是由小程序端传给服务端的，在用户下单时告知服务端应付金额，demo中取值是1，即1分钱
        $input->SetTotal_fee("1");
        $input->SetNotify_url("https://mini.xiutub.com/home/pay/notify");//需要自己写的notify.php
        $input->SetTrade_type("JSAPI");
        //         由小程序端传给后端或者后端自己获取，写自己获取到的，
        $input->SetOpenid('UdhncondJcnkJnjknkcssdcAbckn');
        //$input->SetOpenid($this->getSession()->openid);
        //         向微信统一下单，并返回order，它是一个array数组
        $order = WxPayApi::unifiedOrder($input);
        //         json化返回给小程序端
        header("Content-Type: application/json");
        echo $this->getJsApiParameters($order);
    }

    private function getJsApiParameters($UnifiedOrderResult)
    {    //判断是否统一下单返回了prepay_id
        if (!array_key_exists("appid", $UnifiedOrderResult)
            || !array_key_exists("prepay_id", $UnifiedOrderResult)
            || $UnifiedOrderResult['prepay_id'] == ""
        ) {
            throw new WxPayException("参数错误");
        }
        $jsapi = new WxPayJsApiPay();
        $jsapi->SetAppid($UnifiedOrderResult["appid"]);
        $timeStamp = time();
        $jsapi->SetTimeStamp("$timeStamp");
        $jsapi->SetNonceStr(WxPayApi::getNonceStr());
        $jsapi->SetPackage("prepay_id=" . $UnifiedOrderResult['prepay_id']);
        $jsapi->SetSignType("MD5");
        $jsapi->SetPaySign($jsapi->MakeSign());
        $parameters = json_encode($jsapi->GetValues());
        return $parameters;
    }

    /**
     * 回调
     */
    public function notify()
    {
        log::write("666", "test");
        $notify = new \Notify_pub();
        //存储微信的回调
        $xml = file_get_contents('php://input');//$GLOBALS['HTTP_RAW_POST_DATA'];      
        $notify->saveData($xml);

        if ($notify->checkSign() == FALSE) {
            log::write("777", "test");
            $notify->setReturnParameter("return_code", "FAIL");//返回状态码
            $notify->setReturnParameter("return_msg", "签名失败了啊");//返回信息
        } else {
            log::write("888", "test");
            $notify->setReturnParameter("return_code", "SUCCESS");//设置返回码
        }

        if ($notify->checkSign() == TRUE) {
            log::write(json_encode($notify), 'order');
            if ($notify->data["result_code"] == "SUCCESS") {
                $out_trade_no = $notify->data['out_trade_no'];//商户订单号

                $res['order_no'] = $notify->data["transaction_id"];//订单号
                $res['order_type'] = 2;//微信支付
                $res['commit_time'] = time();//交易付款时间
                $res['pay_status'] = 1;//支付状态 0表示未支付
                $r = M("pay_order")->where(["out_trade_no" => $out_trade_no])->save($res);
                log::write($r, "result");


            }
        }
    }
}